package com.ncepu.clubmanagement.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;

@Component
public  class JwtUtils {

    @Value("${secret}")
    private String secretString;
    public String generateJWT(HashMap<String, Object> jwtMap){
//        SecretKey key = HS256.key().build();
//        String secretString = Encoders.BASE64.encode(key.getEncoded());
        SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));


        String jwt = Jwts.builder()
                .signWith(secretKey)   // 签名(指定加密算法)(可以看作头部)
                .claims().add(jwtMap)  // 添加载荷(中间部分)
                .and()
                .expiration(new Date(System.currentTimeMillis() + 3600 * 1000 * 6))
                .compact();

        return jwt;

    }

    public Claims parseJWT(String jwt){

        SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

        Claims claims = Jwts.parser()
                .verifyWith(secretKey)
                .build()
                .parseSignedClaims(jwt).getPayload();

        return claims;
    }

}
